/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.authorize.domain.repository;

import org.cshoo.tattoo.authorize.domain.po.Menu;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author 杨翼
 * @since 1.0
 */
public interface IMenuRepository extends CrudRepository<Menu, Long> {

    @Query("update Menu menu set menu.name = :#{#menu.name}, menu.description = :#{#menu.description}, menu.uri = :#{#menu.uri}, menu.lastModifiedBy = :#{#menu.lastModifiedBy}, menu.lastModifiedDate = :#{#menu.lastModifiedDate} where menu.id = :#{#menu.id}")
    @Transactional
    @Modifying
    void updateMenu(Menu menu);

    @Query("SELECT menu FROM Menu menu where menu.appId=:#{#appId} and menu.parentId is null")
    List<Menu> findRootMenuByApp(Long appId);

    List<Menu> findByAppId(Long appId);

    List<Menu> findMenusByParentId(Long parentId);

    Menu findByCodeAndAppId(String code, Long appId);

    @Query("select menu from Menu menu inner join RoleMenuRelation rmr on menu.id = rmr.menuId where rmr.roleId = ?1")
    List<Menu> findByRoleId(Long roleId);

    @Query("select menu from Menu menu inner join RoleMenuRelation rmr on menu.id = rmr.menuId where rmr.roleId in ?2 and menu.appId = ?1")
    List<Menu> findByAppIdAndRoleIds(Long appId, List<Long> roleId);

    List<Menu> findByType(int type);

    @Query("select menu from Menu menu where menu.appId=:#{#appId} and menu.parentId is null")
    List<Menu> findRootMenus(Long appId);
}
